﻿using Microsoft.AspNetCore.Mvc;
using Queer.Util.Model;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin.MP.Helpers;
using System.Threading.Tasks;

namespace Queer.WebApi.Areas.WeixinMP.MainManage
{
    /// <summary>
    /// 主要控制器
    /// </summary>
    public class MainController : BaseWeixinMPController
    {
        /// <summary>
        /// 获取JS SDK 签名
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<TData> GetJsSdkUiPackageAsync()
        {
            // 注意URL 是页面的URL。踩坑
            var jssdkUiPackage = await JSSDKHelper.GetJsSdkUiPackageAsync(appId, appSecret, "http://pubpaperstest.zhyinfo.cn/weixin/weixinLogin.html");

            TData<JsSdkUiPackage> data = new()
            {
                Data = jssdkUiPackage,
                Tag = 1
            };

            return data;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<TData> GetUserInfo(string code)
        {
            //通过，用code换取access_token
            var result = await OAuthApi.GetAccessTokenAsync(appId, appSecret, code);

            // 因为第一步选择的是OAuthScope.snsapi_userinfo，这里可以进一步获取用户详细信息
            var userInfo = OAuthApi.GetUserInfo(result.access_token, result.openid);

            TData<OAuthUserInfo> obj = new()
            {
                Tag = 1,
                Data = userInfo
            };

            return obj;
        }
    }
}